import { _decorator, Component, instantiate, Prefab, v3, view } from 'cc';
import { command } from './FunctionStore';
import { MessagePipe } from './MessagePipe';
const { ccclass, property } = _decorator;

@ccclass('NewComponent')
export class NewComponent extends Component {
    @property(Prefab)
    prefab: Prefab = null!;

    start() {
        this.test2();
    }

    test1() {
        command.add('print', this.print);
        command.add('spawn', this.spawn);
        command.add('add', this.add);
        this.scheduleOnce(() => {
            for (let i = 0; i < 10; i++) {
                command.call('spawn', this);
            }
            command.call('print', this, 123, 'hello', {
                id: 0,
                name: 'world',
            });
            let v = command.call('add', this, 1, 2);
            console.log(v);
        }, 2);
    }

    test2() {
        // 示例使用：
        const pipe = new MessagePipe();
        // 在父页面接收消息
        pipe.onMessage('message1', (data) => {
            console.log('收到消息 message1:', data);
        });
        pipe.onMessage('message2', (data) => {
            console.log('收到消息 message2:', data);
        });
        pipe.onMessage('message3', (data) => {
            console.log('收到消息 message3:', data);
        });

        this.scheduleOnce(() => {
            // 在子页面1发送消息到父页面
            pipe.sendMessage(window, 'message1', { someData: 'Hello 1' });
            pipe.sendMessage(window, 'message2', { someData: 'Hello 2' });
            pipe.sendMessage(window, 'message3', { someData: 'Hello 3' });
        }, 2);
    }

    print(...arg: any[]) {
        console.log(arg);
        return arg;
    }

    add(a: number, b: number) {
        return a + b;
    }

    spawn() {
        const node = instantiate(this.prefab);
        this.node.addChild(node);
        const size = view.getVisibleSize();
        const x = Math.random() * size.width - size.width / 2;
        const y = Math.random() * size.height - size.height / 2;
        node.position = v3(x, y);
        return node;
    }
}
